import json
import math
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

joy_event_project_api = Blueprint('joy_event_project_api', __name__)
joy_event_project_down_api = Blueprint('joy_event_project_down_api', __name__)
joy_event_project_sync_api = Blueprint('joy_event_project_sync_api', __name__)


@joy_event_project_api.route('/joy_event_project', methods=['POST'])
def joy_event_project():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'detail':
        query = JoyEventProject.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'tab': json.loads(query.tab)
        }
        result_data['data']['item'] = tmp

    elif _action == 'doc_id_list':
        doc_file_data = GetDocByFilename('cost_event')
        result = []
        for k, v in doc_file_data.items():
            result.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
            })
        return json.dumps(result)

    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        '''joy_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        reward = json.loads(joy_event_project_data.reward)'''
        if _part == 'basic':
            JoyEventProject.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'tab':
            JoyEventProject.query.filter_by(project=_project).update({
                'tab': json.dumps(_data)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    return jsonify(result_data)


@joy_event_project_down_api.route('/joy_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def joy_event_project_down(is_push):
    def get_tab_doc(tab_index):
        doc_map = {
            '0': {
                '1': 'Use Gold',
                '2': 'Gold benutzen',
                '3': "Utiliser de l'Or",
                '4': 'Usar Ouro',
                '5': 'Uar Oro',
                '7': '使用金币',
                '8': '使用金幣',
                '13': '골드 사용',
                '15': 'Usa Oro',
                '16': 'ゴールドを使う'
            },
            '1': {
                '1': 'Use Speedups',
                '2': 'Beschleuniger benutzen',
                '3': 'Utiliser des Accélérations',
                '4': 'Usar Acelerações',
                '5': 'Uar Aceleraciones',
                '7': '使用加速',
                '8': '使用加速',
                '13': '스피드업 사용',
                '15': 'Usa Velocizzazioni',
                '16': 'スビートアップを使う'
            },
            '2': {
                '1': 'Accumulated Logins',
                '2': 'Kumulierte Anmeldungen',
                '3': 'Connexions Accumulées',
                '4': 'Logins Acumulados',
                '5': 'Inicios de Sesión Acumulados',
                '7': '累计登录',
                '8': '累計登錄',
                '13': '누적 로그인',
                '15': 'Accessi Accumulati',
                '16': '累計ログイン回数'
            }
        }
        res = {}
        for lang_index in range(1, 22):
            if str(lang_index) in doc_map[str(tab_index)]:
                res[str(lang_index)] = doc_map[str(tab_index)][str(lang_index)]
            else:
                res[str(lang_index)] = doc_map[str(tab_index)]['1']
        return res

    def get_task_doc(tab_index, target):
        doc_map = {
            '0': {
                '1': 'Use %s Gold in total',
                '2': 'Nutze insgesamt %s Gold',
                '3': 'Utiliser %s Or au total',
                '4': 'Use %s de ouro no total',
                '5': 'Usa %s de Oro en total',
                '7': '累计使用%s金币',
                '8': '累計使用%s金幣',
                '13': '총 %s 골드 사용',
                '15': 'Usa %s oro in totale',
                '16': '合計で%sゴールドを使う'
            },
            '1': {
                '1': 'Use Speedups accumulated to %s Days',
                '2': 'Nutze Beschleuniger kumuliert für %s Tage',
                '3': 'Accélérations Accumulées à %s Jours',
                '4': 'Use Acelerações acumuladas para %sD',
                '5': 'Usa Aceleraciones acumuladas a %sD',
                '7': '累计使用%s天加速',
                '8': '累計使用%s天加速',
                '13': '%s일까지 누적된 스피드업 사용',
                '15': 'Uso di velocizzazioni accumulato a %s giorni',
                '16': '累計%s日のスピードアップを使う'
            },
            '2': {
                '1': 'Accumulated Logins to %sD',
                '2': 'Kumulierte Anmeldungen zu %sT',
                '3': 'Connexions Accumulées à %sJ',
                '4': 'Logins acumulados para %sD',
                '5': 'Inicios de Sesión Acumulados a %sD',
                '7': '累计登陆%s天',
                '8': '累計登陸%s天',
                '13': '%s일 누적 로그인',
                '15': 'Accessi accumulati a %sgg',
                '16': '累計%s日ログインする'
            }
        }
        res = {}
        for lang_index in range(1, 22):
            if str(lang_index) in doc_map[str(tab_index)]:
                res[str(lang_index)] = doc_map[str(tab_index)][str(lang_index)] % target
            else:
                res[str(lang_index)] = doc_map[str(tab_index)]['1'] % target
        return res

    def get_rule_list(rl):
        rl_map = {
            '1': [{"detail": [], "factor": [-1, 1], "type": 26}],
            '2': [{"detail": [], "factor": [0, 1], "type": 10}],
            '3': [{"detail": [], "factor": [0, 1], "type": 27}],
            '4': [{"detail": [[0, 0, [96]]], "factor": [0, 1], "type": 31}],
            '5': [{"detail": [[0, 0, [95]], [1, 0, [1, 2, 3, 4, 5]]], "factor": [0, 1], "type": 31}],
            '6': [{"detail": [[0, 0, [0]], [1, 0, [1764]]], "factor": [0, 1], "type": 31}]
        }
        return rl_map[str(rl)]

    def get_task_type(rl):
        rl_map = {
            '1': 0,
            '2': 0,
            '3': 1,
            '4': 0,
            '5': 0,
            '6': 0
        }
        return rl_map[str(rl)]

    def get_title_doc():
        doc_map = {
            '1': 'Bundle of Joy & Riches',
            '2': 'Spaß & Reichtum im Bündel',
            '3': 'Paquet de joie & richesse',
            '4': 'Pacote de Alegrias e Riquezas',
            '5': 'Paquete de Alegría y Riquezas',
            '7': '欢乐派对，轻松赢奖',
            '8': '歡樂派對，輕鬆贏獎',
            '13': '기쁨과 풍요의 보따리',
            '15': 'Fascio di Gioia e Ricchezze',
            '16': '喜びと宝の山'
        }
        res = {}
        for lang_index in range(1, 22):
            if str(lang_index) in doc_map:
                res[str(lang_index)] = doc_map[str(lang_index)]
            else:
                res[str(lang_index)] = doc_map['1']
        return res

    result = {}

    query = JoyEventProject.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        tab_data = json.loads(q.tab)

        _tab = []
        for i in range(0, len(tab_data)):
            _task_list = []
            for j in tab_data[i]['task_list']:
                if i == 1:
                    _doc = get_task_doc(i, math.floor(j['target'] / 86400))
                else:
                    _doc = get_task_doc(i, j['target'])
                _task_list.append({
                    'doc': _doc,
                    'reward': RewardToTMysqlNew(j['reward']),
                    'rule_list': get_rule_list(j['rule_list']),
                    'target': j['target'],
                    'task_type': get_task_type(j['rule_list'])
                })
            _tab.append({
                'doc': get_tab_doc(i),
                'task_list': _task_list
            })
        result[str(_project)] = {
            'calendar_conf': {
                'event_type': 28,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': basic['calendar_doc_id'],
                    'info': basic['calendar_doc_id']
                },
                'reward': RewardToTMysqlNew(basic['calendar_reward']),
                'show_type': 0
            },
            'basic': {
                'castle_lv': basic['castle_lv'],
                'event_ui': basic['event_ui'],
                'lable_end': basic['lable_end'],
                'main_button_end': basic['main_button_end'],
                'title': get_title_doc()
            },
            'info': {
                'tab': _tab
            }
        }

    response = DownLoad('joy_event_proj', result, is_push)

    return response


@joy_event_project_sync_api.route('/joy_event_project_sync/', methods=['GET', 'POST'])
def joy_event_project_sync():
    reward_list = rewardList()

    def RewardShowToDocBonus3(reward_list, reward_item_list={}):
        if len(reward_item_list) == 0:
            reward_item_list = rewardList()
        result_bonus = []
        for x in range(len(reward_list)):
            item_type = reward_list[x]['a'][0]
            item_id = reward_list[x]['a'][1]
            item_num = reward_list[x]['a'][2]
            # print(item_type in reward_item_list)
            if item_type in reward_item_list['name'] and str(item_id) in reward_item_list['name'][item_type]:
                item_name = reward_item_list['name'][item_type][str(item_id)]
                item_price = 0
                for z in reward_item_list['reward'][item_type]:
                    if z['id'] == int(item_id):
                        item_price = z['price']
                        break
            else:
                item_name = 'ERROR'
                item_price = 0
            # tmp = {"id": item_id, "name": str(item_id) + ' - ' + item_name, "num": item_num, "price": item_price, "type": item_type}
            tmp = {"id": item_id, "name": item_name, "num": item_num, "price": item_price, "type": item_type}
            result_bonus.append(tmp)
        return result_bonus
    def get_reward_info(r, index):
        if len(r) < index + 1:
            return []
        result = RewardShowToDocBonus3(r[index], reward_list)
        return result

    data = {}
    with open(STATIC_PATH + '../sync/joy_event_proj_preprocessing.json', encoding='utf8') as f:
        data = json.load(f)
    print('data length:', len(data))
    _currentIndex = 0
    for i in data:
        _currentIndex += 1
        print('handler: ' + str(_currentIndex) + ' / ' + str(len(data)))
        _project = int(i)
        basic = data[i]['basic']
        tab = data[i]['info']['tab']
        _remark = str(_project)

        _tab = []
        for t in tab:
            _task_list = []
            for task in t['task_list']:
                if task['rule_list'][0]['type'] == 26:
                    _rule_list = 1
                elif task['rule_list'][0]['type'] == 10:
                    _rule_list = 2
                elif task['rule_list'][0]['type'] == 27:
                    _rule_list = 3
                else:
                    print(task['rule_list'])
                    raise Exception('Unable to parse rule_list')
                _task_list.append({
                    'reward': RewardShowToDocBonus3(task['reward'], reward_list),
                    'target': task['target'],
                    'rule_list': _rule_list
                })
            _tab.append({
                'task_list': _task_list
            })


        new_project_data = JoyEventProject(
            project=_project,
            basic=json.dumps({
                'calendar_doc_id': 1,
                'calendar_reward': [],
                'castle_lv': basic['castle_lv'],
                'event_ui': basic['event_ui'],
                'lable_end': basic['lable_end'],
                'main_button_end': basic['main_button_end']
            }),
            tab=json.dumps(_tab),
            remark=_remark
        )
        db.session.add(new_project_data)
    db.session.commit()
    return jsonify({'msg': 'finished'})
